package cn.itcast.work.controller.system_management;

import cn.itcast.work.dao.system.TextMapper;
import cn.itcast.work.pojo.*;
import cn.itcast.work.service.system_service.SystemService;
import cn.itcast.work.service.user_service.UserService;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 后台管理系统
 */
@Slf4j
@Controller//添加到ioc容器
@RequestMapping("/system")
public class ManagerController {

    /**
     * 进入后端接口
     *
     * @param model
     * @return
     */
    @RequestMapping("into")
    public String into(Model model) {
        int currentPage = 1;
        int totalCount = textMapper.selectAllBook();
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        List<Map<String, Object>> orderByPage = textMapper.selectBooksByPage((currentPage - 1) * pageSize, pageSize);
        System.out.println(orderByPage);
        model.addAttribute("allBooks", orderByPage);
        model.addAttribute("booksTotal", totalPage);
        model.addAttribute("current", currentPage);
        model.addAttribute("m", 0);
        return "system2";
    }

    /**
     * 返回用户界面
     *
     * @return
     */
    @RequestMapping("showMain")
    public String showMain() {
        return "main";
    }

    @Resource(name = "systemService")
    private SystemService systemService;

    @Resource(name = "userService")
    private UserService userService;

    /**
     * 动态搜索文章 分页展示
     *
     * @param search
     * @param t
     * @return
     */
    @RequestMapping("searchText")
    @ResponseBody
    public MyResponse searchText(String search, int t) {
        log.info("动态 搜索文章:{}", search);
//        使用分页查询
        int totalCount = textMapper.selectAllSearch(search);
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        List<Map<String, Object>> list = systemService.toSearchText(search, (t - 1) * pageSize, pageSize);
        if (list.size() != 0) {
            return new MyResponse(list, totalPage, HttpStatus.OK);
        }
        //否则无反应
        return new MyResponse(HttpStatus.NO_CONTENT);
    }


    /**
     * 动态搜索用户 分页展示
     *
     * @param search
     * @param t
     * @return
     */
    @RequestMapping("searchUsers")
    @ResponseBody
    public MyResponse searchUsers(String search, int t) {
        log.info("动态 搜索用户:{}", search);
        int totalCount = textMapper.selectAllUsers(search);

        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        if (totalPage < 1) {
            totalPage = 1;
        }
        List<Map<String, Object>> list = textMapper.toSearchUser(search, (t - 1) * pageSize, pageSize);
        if (list.size() != 0) {
            return new MyResponse(list, totalPage, HttpStatus.OK);
        }
        //否则无反应
        return new MyResponse(HttpStatus.NO_CONTENT);
    }

    /**
     * 后台管理
     * 管理文章
     * 1.推送到首页
     * 2.撤下首页
     * 3.删除
     * 管理用户
     * 1.推送
     * 2.封号 删除
     */
//    //入口  查home_page
//    @RequestMapping("/door")
//    public String toSystem(HttpSession session) {
////        查询用户
////        List<User> userList = systemService.selectAllUser();
////        session.setAttribute("allusers",userList);
////        //查询博客
////        List<TextWhole> list = systemService.toselectAllText();
////        session.setAttribute("alltext",list);
//
//        List<String> textShowList = systemService.toSelectPutTitle();
//        System.out.println("首页表：里的名字");
//        textShowList.forEach(text -> System.out.println(text));
//        List<User_show> user_showList = systemService.toSelctPutUser();
//        session.setAttribute("putUser", user_showList);
//        session.setAttribute("putText", textShowList);
//        return "system";
//    }

    //显示推送的文章
    //显示被推送的博主
//    @RequestMapping("/showPut")
//    public String showPut(HttpSession session) {
//        //查询 数据库
//        List<String> textShowList = systemService.toSelectPutTitle();
//        List<User_show> user_showList = systemService.toSelctPutUser();
//        session.setAttribute("putUser", user_showList);
//        session.setAttribute("putText", textShowList);
//        return "system";
//    }
//    @RequestMapping("manageText")
//    @ResponseBody
//    public List<TextWhole> manageText(Model model) {
//        //查询所有文章
//        return systemService.toselectAllText();
//    }

    /**
     * 推送文章
     *
     * @param phone
     * @param title
     * @return
     */
    @RequestMapping("putText")
    //推送文章
    public String putText(String phone, String title, int t, int put, Model model) {
        //推送文章
        log.info("管理员推送作者：{},文章{}", phone, title);
        textMapper.putText(phone, title, put);
        int totalCount = textMapper.selectAllBook();

        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        List<Map<String, Object>> orderByPage = textMapper.selectBooksByPage((t - 1) * pageSize, pageSize);
//        System.out.println(orderByPage);
        model.addAttribute("allBooks", orderByPage);
        model.addAttribute("booksTotal", totalPage);
        model.addAttribute("current", t);
        model.addAttribute("m", 0);
        return "system2";
    }

//    @RequestMapping("cancelText/{title}")
//    //撤下首页文章
//    public ModelAndView cancelText(@PathVariable String title) {
//        //将数据存入首页表
//        System.out.println("title = " + title);
//        ModelAndView mv = new ModelAndView();
//        //存入数据库
//        if (systemService.toCancel(title)) {
//            mv.addObject("systemInf", "操作成功");
//            mv.addObject("state", "已撤回");
//            mv.setViewName("forward:/WEB-INF/jsp/system.jsp");
//            return mv;
//        }
//        mv.addObject("systemInf", "操作失败");
//        mv.setViewName("forward:/WEB-INF/jsp/system.jsp");
//        return mv;
//    }

    //删除博客
    @RequestMapping("deleteText/{phone}/{title}")
    //删除文章
    public String deleteText(@PathVariable String phone, @PathVariable String title, Model model) {
        System.out.println("phone = " + phone + ", title = " + title);
        //进行转发到index;
        //数据库
        ModelAndView mv = new ModelAndView();
        if (systemService.toDelete(phone, title)) {
            model.addAttribute("systemInf", "操作成功");
            mv.addObject("state", "已删除");
            return "forward:/WEB-INF/jsp/system.jsp";
        }
        model.addAttribute("systemInf", "操作失败");
        return "forward:/WEB-INF/jsp/system.jsp";
    }

    /**
     * 显示推送的文章
     *
     * @return
     */
    @RequestMapping("/showPutText")
    public ResponseEntity<List<Text_show>> showPutText() {
        log.info("显示推荐文章");
        //查询数据库 显示首页表中的所有:联合了多张表
        //先得到home_page
        List<Text_show> list = systemService.selectPutText();
        if (list.size() != 0) {
            return new ResponseEntity<>(list, HttpStatus.OK);
        }
        //否则无反应
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

//
//    //写博客
//    @RequestMapping("/writeBlog")
//    public String writeBlog() {
//        return "editor";
//    }
//

//    //    //显示所有用户
//    @RequestMapping("manageUser")
//    @ResponseBody
//    public List<User> manageUser() {
//        //查询所有文章
//        return systemService.selectAllUser();
//        //处理文章
////        return null;
//    }

    /**
     * 推送/撤下用户
     *
     * @param phone
     * @param put
     * @return
     */
    @RequestMapping("/putUser")
    public String putUser(String phone, int put, int t, Model model) {
        //将数据存入首页表
        log.info("管理员推送用户(0:撤下；1：推送){}", phone);
        textMapper.putUser(phone, put);

        int totalCount = textMapper.selectAllUser();
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        if (totalPage < 1) {
            totalPage = 1;
        }
        log.info("被除数{}", totalPage);
        List<Map<String, Object>> orderByPage = textMapper.selectUsersByPage((t - 1) * pageSize, pageSize);
//        System.out.println(orderByPage);
        model.addAttribute("allOrders", orderByPage);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", t);
        model.addAttribute("m", 1);
        return "system2";
    }

//    @RequestMapping("cancelUser/{name}")
//    //撤下首页用户
//    public ModelAndView cancelUser(@PathVariable String name) {
//        //将数据存入首页表
//        System.out.println("user = " + name);
//
//        ModelAndView mv = new ModelAndView();
//        //存入数据库
//        if (systemService.toCancelUser(name)) {
//            mv.addObject("userInf", "操作成功");
//            mv.setViewName("forward:/WEB-INF/jsp/system.jsp");
//            return mv;
//        }
//        mv.addObject("userInf", "操作失败");
//        mv.setViewName("forward:/WEB-INF/jsp/system.jsp");
//        return mv;
//    }


    /**
     * 显示推荐的用户
     *
     * @return
     */
    @RequestMapping("showUser")
    public ResponseEntity<List<User>> showPutUser() {
        log.info("显示推荐的用户");
        //查询数据库 显示首页表中的所有
//        List<Text_show> list =systemService.selectPutText();
        List<User> list = systemService.toSelctPutUser();
//        list.forEach(user -> System.out.println(user));
        if (list.size() != 0) {
            return new ResponseEntity<>(list, HttpStatus.OK);
        }
        //否则无反应
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Autowired
    TextMapper textMapper;

    /**
     * 分页查询用户
     *
     * @return
     */
    @GetMapping("/users")
    public String getUsers(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "-1") int se,
                           Model model) {
//        共多少用户
        if (se == 0) {
//            上一页
            currentPage = currentPage - 1;
        }
        if (se == 1) {
//            下一页
            currentPage = currentPage + 1;
        }
        int totalCount = textMapper.selectAllUser();
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        if (totalPage < 1) {
            totalPage = 1;
        }
        log.info("被除数{}", totalPage);
        List<Map<String, Object>> orderByPage = textMapper.selectUsersByPage((currentPage - 1) * pageSize, pageSize);
//        System.out.println(orderByPage);
        model.addAttribute("allOrders", orderByPage);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("m", 1);

        return "system2";
    }

    /**
     * 分页查询文章
     *
     * @param currentPage
     * @param se
     * @param model
     * @return
     */
    @GetMapping("/books")
    public String getBooks(@RequestParam(defaultValue = "1") int currentPage, @RequestParam(defaultValue = "-1") int se,
                           Model model) {
//        Page<User> users = userService.getUsers(page, size);
//        共多少用户
        if (se == 0) {
//            上一页
            currentPage = currentPage - 1;
        }
        if (se == 1) {
//            下一页
            currentPage = currentPage + 1;
        }
        int totalCount = textMapper.selectAllBook();
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        List<Map<String, Object>> orderByPage = textMapper.selectBooksByPage((currentPage - 1) * pageSize, pageSize);
//        System.out.println(orderByPage);
        model.addAttribute("allBooks", orderByPage);
        model.addAttribute("booksTotal", totalPage);
        model.addAttribute("current", currentPage);
        model.addAttribute("m", 0);
        return "system2";
    }

    /**
     * 显示详情文章
     *
     * @param title
     * @param request
     * @return
     */
    @RequestMapping(value = "/showDetail", produces = "text/html;charset=utf-8")
    public String showmarkdown(String title, String phone, HttpServletRequest request, Model model) {
        log.info("管理员 查看用户：{}---的文章:{}", phone, title);
        //2.通过参数带回 可以用到全局
        TextWhole textWhole = textMapper.toSee(title, phone);
        model.addAttribute("textWhole", textWhole);
        return "bookCheck";

    }

    /**
     * 审核文章
     *
     * @param choice
     * @return
     */
    @GetMapping("/check")
    public String checkText(int choice, String phone, int t, String title, Model model) {
        log.info("管理员审核文章{}通过1，未通过-1）结果：{}", title, choice);
        log.info("当前页: {}", t);
        textMapper.updateText(choice, phone, title);
        int totalCount = textMapper.selectAllBook();
//      当前的文章显示
        int pageSize = 10;
        int totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
        List<Map<String, Object>> orderByPage = textMapper.selectBooksByPage((t - 1) * pageSize, pageSize);
//        System.out.println(orderByPage);
        model.addAttribute("allBooks", orderByPage);
        model.addAttribute("booksTotal", totalPage);
        model.addAttribute("current", t);
        model.addAttribute("m", 0);
        return "system2";
    }
}
